package cn.blog.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private String contentPath;// 文章路径
	private ThreadLocal<HttpServletRequest> req = new ThreadLocal<>();// HttpServletRequest线程
	private ThreadLocal<HttpServletResponse> resp = new ThreadLocal<>();// HttpServletResponse线程
	private final String PARAM_KEY = "_paramKey_";

	@Override
	protected final void service(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		try {
			this.contentPath = arg0.getContextPath();// 获取路径
			// 设置编码
			arg0.setCharacterEncoding("UTF-8");
			arg1.setCharacterEncoding("UTF-8");

			arg0.setAttribute("blogSystem", this.contentPath);
			req.set(arg0);
			resp.set(arg1);

			HashMap<String, Object> params = (HashMap<String, Object>) arg0.getSession().getAttribute(PARAM_KEY);
			if (params != null && !params.isEmpty()) {
				for (Entry<String, Object> e : params.entrySet()) {
					arg0.setAttribute(e.getKey(), e.getValue());
				}
			}
			super.service(arg0, arg1);

		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(arg0, arg1);
	}
	
	protected final void forward(String viewName)throws ServletException, IOException {
		req.get().getRequestDispatcher("/WEB-INF/" + viewName + ".jsp").forward(req.get(), resp.get());
	}
	
	public final void redirect(String uri) throws IOException {
		// 澶勭悊閲嶅畾鍚�
		resp.get().sendRedirect(this.contentPath + uri);
	}
	
	public final void redirect(String uri, HashMap<String, Object> params) throws IOException {
		
		req.get().getSession().setAttribute(this.PARAM_KEY, params);
		this.redirect(uri);
	}
}
